#!/usr/bin/env python
#coding=utf-8
import cv2
import cv
import os
import math

#设置下一段的起点(ms 为单位)
def _setNextTime(vc,number):
    vc.set(cv.CV_CAP_PROP_POS_MSEC,number)

#设置下一帧的位置
def _setNextFrame(vc,number):
    vc.set(cv.CV_CAP_PROP_POS_FRAMES,number)

#获取总共的帧数
def _getTotalFrame(vc):
    return int(vc.get(cv.CV_CAP_PROP_FRAME_COUNT))

#获取帧率
def _getFPS(vc):
    return vc.get(cv.CV_CAP_PROP_FPS)


#获取总时间
def _getTotalTime(vc):
    frame = _getTotalFrame(vc)
    rate = _getFPS(vc)
    return int(1000*frame/rate)

#保存区间内的图
def _printImg(vc,start,end,gap):
    for index in range(start,end,gap):
        _setNextFrame(vc,index)
        rval,frame = vc.read()
        if(rval):
            name = "./image"+str(index)+".jpg"
            cv2.imwrite(name,frame)
            print name
        cv2.waitKey(1)#正数表示会延时一段时间, 时间根据系统线程切换来定,ms 级别,不会是准确的 ms

#保存时间区间内的图
def _printImgMs(vc,start,end,gap):
    fps = 1000/_getFPS(vc)
    if gap < fps:
        gap = int(math.ceil(fps))
    if not os.path.exists("./pics"):
        os.mkdir("./pics")
    savePath = os.path.join("./pics/image")
    for index in range(start,end,gap):
        _setNextTime(vc,index)
        rval,frame = vc.read()
        if(rval):
            name = savePath+str(index)+".jpg"
            cv2.imwrite(name,frame)
            print name
        cv2.waitKey(1)#正数表示会延时一段时间, 时间根据系统线程切换来定,ms 级别,不会是准确的 ms

def getPics(mvFile,start,end,gap):
    if os.path.exists(mvFile):
        vc = cv2.VideoCapture(mvFile) #读入视频文件
        if vc.isOpened(): #判断是否正常打开
            # printImg(rval,vc,37000,37000,10)#一段帧数里的
            _printImg(vc,0,_getTotalFrame(vc),500)#全部获取
        vc.release()
    else:
        print "file not found"

def getPics(mvFile="blen.MOV"):
    if os.path.exists(mvFile):
        vc = cv2.VideoCapture(mvFile)
        if vc.isOpened():
            _printImgMs(vc,900,1000,10)
        vc.release()
    else:
        print "file not found"


if __name__=="__main__":
    mvFile = 'blen.MOV'
    getPics()
